package com.example.dsplatform.Service.ipml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dsplatform.Dao.Mapper.MenuMapper;
import com.example.dsplatform.Dao.Mapper.UserMapper;
import com.example.dsplatform.pojo.Entity.LoginUser;

import com.example.dsplatform.pojo.Entity.User;
import com.example.dsplatform.utls.Dmes;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
public class UserDetailsServiceIpml implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private Dmes dmes;

    @Override
    public UserDetails loadUserByUsername(String mes) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> userqy = new LambdaQueryWrapper<>();
        String who = dmes.extractLastCharacter(mes);
        String mesT = dmes.removeLastCharacter(mes);
        if ("p".equals(who)) {
            userqy.eq(User::getPhone, mesT);
        } else if ("i".equals(who)) {
            userqy.eq(User::getId, mesT);
        }

        User user = userMapper.selectOne(userqy);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> list = menuMapper.selectPermbyuserid(user.getId()); // 假设这是你的查询结果
        return new LoginUser(user, list);

    }
}
